<?php

namespace App\Http\Controllers;

use App\Jobs\SendWechatTemplateMsg;
use App\Models\Qrcode;
use App\User;
use Auth;
use EasyWeChat\Message\Article;
use EasyWeChat\Message\News;
use EasyWeChat\Message\Text;
use Log;
use Cache;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use EasyWeChat\OpenPlatform\Guard;

/**
 * 微信相关
 * 本系统设计为只可以绑定一个公众号，重新授权会覆盖之前的信息
 * Class WechatController
 * @package App\Http\Controllers
 */
class WechatController extends Controller
{

    const PRE_QRCODE = 'www.m-union.net.cn_wechat_qrcode_';

    /**
     * 静态变量
     * @var
     */
    private static $app;

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function callback($appid)
    {
        $app = self::app();
        $app->server->setMessageHandler(function ($message) {
//            Log::info('微信消息：' . $message);
            switch ($message->MsgType) {
                case 'event':
                    /*{"ToUserName":"gh_759753d4d5f4","FromUserName":"oHwEGs2nlJMpKJO7Id7-cIJOq7cY","CreateTime":"1497922446","MsgType":"event","Event":"SCAN","EventKey":"56","Ticket":"gQFd7zwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAySkNMRjB1djE4NlAxbEd6Z3hwMVAAAgRqekhZAwQA6QcA"}*/
                    if ($message->Event == 'SCAN' && starts_with($message->EventKey, self::PRE_QRCODE)) {
                        $qrcodeId = intval(str_replace(self::PRE_QRCODE, '', $message->EventKey));
                        $callback = Qrcode::find($qrcodeId);
                        if ($callback) {
                            if (method_exists($callback->className, $callback->method)) {
                                $param = json_decode($callback->param);
                                $param[] = $message->FromUserName;
                                try {
                                    return call_user_func_array($callback->className . '::' . $callback->method, $param);
                                } catch (\Exception $exception) {
                                }
                            };
                        }
                    }
                    break;
                case 'text':
                    Log::notice('收到一条消息：' . $message);
                    return $this->feedback($message);
                    break;
                case 'image':
                    break;
                case 'voice':
                    break;
                case 'video':
                    break;
                case 'location':
                    break;
                case 'link':
                    break;
                default:
                    break;
            }
        });
        return $app->server->serve();
    }

    /**
     * 第三方平台绑定微信公众号
     * @param Application $wechat
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function bind(Application $wechat)
    {
        $openPlatform = $wechat->open_platform;
        $response = $openPlatform->pre_auth->redirect('https://weapp.meizucampus.com/wechat/auth');
        return $response;
    }

    /**
     * 微信公众号授权，待测试
     * @param Application $wechat
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function auth(Application $wechat)
    {
        // $wechat 则为容器中 EasyWeChat\Foundation\Application 的实例
        $openPlatform = $wechat->open_platform;
        $server = $openPlatform->server;
        $server->setMessageHandler(function ($event) use ($openPlatform) {
            // 事件类型常量定义在 \EasyWeChat\OpenPlatform\Guard 类里
            switch ($event->InfoType) {
                case Guard::EVENT_AUTHORIZED: // 授权成功
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    Cache::forever('authorizer_appid', $authorizationInfo->authorization_info->authorizer_appid);
                    Cache::forever('authorizer_refresh_token',
                        $authorizationInfo->authorization_info->authorizer_refresh_token);
                    Log::debug('授权成功');
                    Log::debug($authorizationInfo);
                    break;
                // 保存数据库操作等...
                case Guard::EVENT_UPDATE_AUTHORIZED: // 更新授权
                    Log::debug('更新授权');
                    $authorizationInfo = $openPlatform->getAuthorizationInfo($event->AuthorizationCode);
                    Cache::forever('authorizer_appid', $authorizationInfo->authorization_info->authorizer_appid);
                    Cache::forever('authorizer_refresh_token',
                        $authorizationInfo->authorization_info->authorizer_refresh_token);
                    Log::debug($authorizationInfo);
                    break;
                // 更新数据库操作等...
                case Guard::EVENT_UNAUTHORIZED: // 授权取消
                    // 更新数据库操作等...
                    Log::debug('授权取消');
                    break;
            }
        });
        $response = $server->serve();
        return $response;
    }

    //空方法，用于微信登录回调
    public function login()
    {

    }

    /**
     * 更新所有成员的微信头像
     */
    public function headimgurl()
    {
        $userService = self::app()->user;
        $users = User::all();
        foreach ($users as $user) {
            $openid = $user->openid;
            if (!empty($openid)) {
                $u = $userService->get($openid);
                $user->headimgurl = $u->headimgurl;
                echo $u->headimgurl . '<br>';
                $user->save();
            }
        }

    }

    /**
     * 获取参数二维码
     * @param $tokenID
     * @param int $expire
     * @return array URL 和二维码URL
     */
    public static function qrcode($key, $className, $method, $param)
    {
        $expire = 24 * 3600;
        Cache::forget($key);
        $qrcodeID = Cache::get($key);
        if ($qrcodeID) {
            $qrcode = Qrcode::find($qrcodeID);
            if ($qrcode) {
                return [$qrcode->url, $qrcode->img];
            }
        }

        $callback = new Qrcode();
        $callback->className = $className;
        $callback->method = $method;
        $callback->param = json_encode($param);
        $callback->save();
        $qrcode = self::app()->qrcode;
        $result = $qrcode->temporary(self::PRE_QRCODE . $callback->id, $expire / 60);
        $ticket = $result->ticket;
        $url = $result->url;
        $img = $qrcode->url($ticket);
        $callback->url = $url;
        $callback->img = $img;
        $callback->expire = $expire;
        $callback->save();
        Cache::put($key, $callback->id, $expire);
        return [$url, $img];
    }

    /**
     * @return Application
     */
    public static function app()
    {
        if (self::$app == null) {
            $wechat = app('wechat');
            $authorizerAppId = env('AUTHORIZER_APPID');
            $authorizerRefreshToken = env('AUTHORIZER_REFRESH_TOKEN');
            self::$app = $wechat->open_platform->createAuthorizerApplication($authorizerAppId, $authorizerRefreshToken);
        }
        return self::$app;
    }

    public function user($openid)
    {
        return response()->json($this->getUserInfo($openid));
    }

    /**
     * 反馈机制
     * @param $message
     */
    private function feedback($message)
    {
        $app = self::app();
        $adminOpenids = env('OPENID_FEEDBACK_TO');
        $admins = explode(',', $adminOpenids);
        if (starts_with($message->Content, '我要反馈')) {
            $userInfo = $this->getUserInfo($message->FromUserName);
            $name = empty($userInfo) ? '未知' : $userInfo->nickname;
            $msg = new News([
                'title' => '[我要反馈]' . $name,
                'description' => mb_substr($message->Content, 4),
            ]);
            Log::notice('反馈：' . $name . ' ' . $message->Content);
//            $text = new Text(['content' => '反馈人：' . $name . "\n反馈内容：" . mb_substr($message->Content, 4) . "\n反馈时间：" . date('Y-m-d H:i:s')]);
            foreach ($admins as $admin) {
                dispatch(new SendWechatTemplateMsg(__CLASS__ . '::sendFeedBackToAdmin', [$msg, $admin]));
//                $app->staff->message([$msg])->to($admin)->send();
            }
            return '反馈成功，我们收到消息后会及时处理[愉快]';
        }
        return '';
    }

    /**
     * @param $openid
     * @return \EasyWeChat\Support\Collection
     */
    private function getUserInfo($openid)
    {
        return self::app()->user->get($openid);
    }

    /**
     * @param $content
     * @param $admin
     */
    public static function sendFeedBackToAdmin($content, $admin)
    {
        self::app()->staff->message([$content])->to($admin)->send();
    }
}
